﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Empires.CRL.Logger;
using System.Xml.Linq;
using Empires.CRL.DataContract;
using System.Reflection;
using System.Web;
using System.Web.SessionState;
using System.Xml.XPath;
using System.Linq.Expressions;
using System.Collections;

namespace Empires.PL.PageBuilder
{
    /// <summary>
    /// body段解析器
    /// </summary>
    class BodyAnalyzer : IRequiresSessionState
    {
        static List<string> ContractAction = new List<string>();
        static Assembly serviceClient = null;
        static BodyAnalyzer()
        {
            ContractAction = new List<string>() 
            {
                "console",
                //"fail",
                "index","about","news","newsdetail","notice","product","productdetail",
                "business","serviceitem","download","blog","article","online",
            };
            serviceClient = Assembly.LoadFrom(
                AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "bin\\Empires.PL.ServiceClient.dll");
        }
        /// <summary>
        /// 解析入口
        /// </summary>
        /// <param name="rawbodytext"></param>
        /// <param name="templetePath"></param>
        /// <param name="copid">公司id</param>
        /// <returns></returns>
        public static string Analysis(string rawbodytext, string templetePath, string copname)
        {
            string rightsrc = CorrectionSrc(rawbodytext, templetePath); //矫正src
            string righthref = Correctionhref(rightsrc, templetePath, copname); //矫正href
            //string rightjscode = CorrectionJSCoding(righthref, templetePath); //矫正jquery实现得修改src和href
            return AnalysisLabel(righthref, templetePath, copname);
            //return rightjscode;
        }
        static string CorrectionSrc(string rawbodytext, string templetePath)
        {
            Regex reg = new Regex(PageBuilderRegexpLib.SrcPicker, RegexOptions.IgnoreCase);
            MatchCollection matchs = reg.Matches(rawbodytext);
            int addindex = 0;
            Regex matching = new Regex("{:\\w+?}", RegexOptions.IgnoreCase);
            foreach (Match item in matchs)
            {
                string path = item.ToString().Replace("/", "\\");
                if (matching.IsMatch(path) || String.IsNullOrEmpty(path))
                { 
                    continue;
                }
                if (path.Contains("..")) //如果连接中存在..，则找到其正确的地址
                {
                    List<string> piece = path.Split('\\').ToList();
                    int pevtimes = piece.Where(c => c == "..").Count();
                    System.IO.DirectoryInfo dir = new System.IO.FileInfo(templetePath).Directory;
                    for (int i = 0; i < pevtimes; i++)
                    {
                        dir = dir.Parent;
                    }
                    string currentPath = dir.FullName.EndsWith("\\") ? dir.FullName : dir.FullName + "\\";
                    if (!currentPath.Contains(AppDomain.CurrentDomain.SetupInformation.ApplicationBase))
                    {
                        rawbodytext = reg.Replace(rawbodytext, "javascript:;", 1, item.Index + addindex);
                        addindex += currentPath.Length - path.Length;
                    }
                    else
                    {
                        currentPath = currentPath.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "");
                        currentPath += Concat(piece.Where(c => c != "..").ToList());
                        rawbodytext = reg.Replace(rawbodytext, currentPath.StartsWith("\\") ? currentPath : "\\" + currentPath, 1, item.Index + addindex);
                        addindex += currentPath.Length - path.Length;
                    }
                }
                else
                {
                    System.IO.DirectoryInfo dir = new System.IO.FileInfo(templetePath).Directory;
                    string currentPath = dir.FullName.EndsWith("\\") ? dir.FullName : dir.FullName + "\\";
                    currentPath = currentPath.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "");
                    if (currentPath.EndsWith("\\"))
                    {
                        if (path.StartsWith("\\"))
                        {
                            currentPath += path.Substring(1);
                        }
                        else
                        {
                            currentPath += path;
                        }
                    }
                    else
                    {
                        if (path.StartsWith("\\"))
                        {
                            currentPath += path;
                        }
                        else
                        {
                            currentPath += "\\" + path;
                        }
                    }
                    rawbodytext = reg.Replace(rawbodytext, currentPath.StartsWith("\\") ? currentPath : "\\" + currentPath, 1, item.Index + addindex);
                    addindex += currentPath.Length - path.Length;
                }
            }
            return rawbodytext;
        }
        static string Concat(List<string> list)
        {
            StringBuilder sb = new StringBuilder();
            int length = list.Count;
            for (int i = 0; i < length; i++)
            {
                sb.Append(list[i]);
                if (i != length - 1)
                {
                    sb.Append("\\");
                }
            }
            return sb.ToString();
        }
        static string Correctionhref(string rawbodytext, string templetePath,string copname)
        {
            Regex reg = new Regex(PageBuilderRegexpLib.AHrefPicker, RegexOptions.IgnoreCase);
            MatchCollection matchs = reg.Matches(rawbodytext);
            int addindex = 0;
            string path = string.Empty;  //被捕获字段
            string querystring = string.Empty; //页面传参
            string url = string.Empty; //请求地址
            string action = string.Empty; //请求文件
            string realurl = string.Empty; //实际解析后的地址
            foreach (Match item in matchs)
            {
                path = item.ToString().Replace("/", "\\");
                if (path.IndexOf('?') > 0) //检查是否带有参数
                {
                    querystring = path.Substring(path.IndexOf('?'));
                    url = path.Substring(0, path.IndexOf('?'));
                }
                else
                {
                    querystring = string.Empty;
                    url = path;
                }
                if (url.Contains("\\")) //检测是否在其他目录下
                {
                    action = url.Substring(url.LastIndexOf('\\') + 1, url.LastIndexOf('.') - url.LastIndexOf('\\') - 1);
                }
                else
                {
                    action = url.Substring(0, url.LastIndexOf('.'));
                }
                if (ContractAction.Any(c => c.ToLower() == action.ToLower()))
                {
                    //生成url
                    realurl = "/" + action + querystring;
                }
                else
                {
                    //不在约定模板列
                    realurl = "javascript:;";
                }
                rawbodytext = reg.Replace(rawbodytext, realurl, 1, item.Index + addindex);
                addindex += realurl.Length - path.Length;
            }
            return rawbodytext;
        }
        /// <summary>
        /// 目前只支持修改src和href属性，其他暂不做修改
        /// </summary>
        /// <param name="rawbodytext"></param>
        /// <param name="templetePath"></param>
        /// <returns></returns>
        static string CorrectionJSCoding(string rawbodytext, string templetePath)
        {
            Regex reg = new Regex(PageBuilderRegexpLib.JqueryAttrPicker, RegexOptions.IgnoreCase);
            MatchCollection matchs = reg.Matches(rawbodytext);
            int addindex = 0;
            foreach (Match item in matchs)
            {
                string path = item.ToString().Replace("\\", "/");
                if (String.IsNullOrEmpty(path))
                {
                    continue;
                }
                string[] type = path.ToLower().Split(',').Select(c => c.Trim()).ToArray();
                switch (type[0])
                {
                    case "\"src\"": //被捕获为src
                        #region src
                        if (type[1].Contains(".."))
                        {
                            List<string> piece = type[1].Split('/').ToList();
                            int pevtimes = piece.Where(c => c.Contains("..")).Count();
                            System.IO.DirectoryInfo dir = new System.IO.FileInfo(templetePath).Directory;
                            for (int i = 0; i < pevtimes; i++)
                            {
                                dir = dir.Parent;
                            }
                            string currentPath = dir.FullName.EndsWith("/") ? dir.FullName : dir.FullName + "/";
                            if (!currentPath.Contains(AppDomain.CurrentDomain.SetupInformation.ApplicationBase))
                            {   //防止超越app根目录
                                rawbodytext = reg.Replace(rawbodytext, "javascript:;", 1, item.Index + addindex);
                                addindex += currentPath.Length - path.Length;
                            }
                            else
                            {
                                currentPath = currentPath.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "").Replace("\\", "/");
                                currentPath += Concat(piece.Where(c => !c.Contains("..")).ToList()).Replace("\\", "/");
                                rawbodytext = reg.Replace(rawbodytext, type[0] + ",\"" + (currentPath.StartsWith("/") ? currentPath : "/" + currentPath), 1, item.Index + addindex);
                                addindex += currentPath.Length - path.Length;
                            }
                        }
                        else
                        {
                            System.IO.DirectoryInfo dir = new System.IO.FileInfo(templetePath).Directory;
                            string currentPath = dir.FullName.EndsWith("/") ? dir.FullName : dir.FullName + "/";
                            currentPath = currentPath.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "").Replace("\\", "/");
                            if (currentPath.EndsWith("/"))
                            {
                                if (type[1].StartsWith("\"/"))
                                {
                                    currentPath += type[1].Substring(2);
                                }
                                else
                                {
                                    currentPath += type[1].Substring(1);
                                }
                            }
                            else
                            {
                                if (type[1].StartsWith("\"/"))
                                {
                                    currentPath += type[1].Substring(1);
                                }
                                else
                                {
                                    currentPath += "/" + type[1].Substring(1);
                                }
                            }
                            rawbodytext = reg.Replace(rawbodytext, type[0] + "," + (currentPath.StartsWith("\"/") ? currentPath : "\"/" + currentPath), 1, item.Index + addindex);
                            addindex += currentPath.Length - path.Length;
                        }
                        #endregion
                        break;
                    case "\"href\"":
                        break;
                }
            }
            return rawbodytext;
        }
        /// <summary>
        /// 解析empires标签
        /// </summary>
        /// <param name="rawbodytext"></param>
        /// <param name="templetePath"></param>
        /// <param name="copname"></param>
        /// <returns></returns>
        static string AnalysisLabel(string rawbodytext, string templetePath, string copname)
        {
            Regex sreg = new Regex(PageBuilderRegexpLib.LabelPick, RegexOptions.IgnoreCase);
            MatchCollection matchs = sreg.Matches(rawbodytext);
            int addindex = 0;

            Regex empreg = new Regex(PageBuilderRegexpLib.EmpiresLabel, RegexOptions.IgnoreCase);
            foreach (Match item in matchs)
            {
                string element = item.ToString();
                Match method = empreg.Match(element);
                var name = method.Groups["name"].ToString();

                List<DefaultDataPack> data = new List<DefaultDataPack>();
                string html = string.Empty;
                if (name.ToLower() == "system") //如果为系统预定义函数
                {
                    Regex reg = new Regex(PageBuilderRegexpLib.SysMethodLabel, RegexOptions.IgnoreCase);
                    html = InvokeSystemMethod(reg.Match(element).ToString(), copname);
                }
                else
                {
                    data = ReflectionMethod(name, copname);
                    html = FileHTML(element, data);
                }
                rawbodytext = sreg.Replace(rawbodytext, html, 1, item.Index + addindex);
                addindex += html.Length - element.Length;
            }
            return rawbodytext;
        }
        static string InvokeSystemMethod(string name, string copName)
        {
            switch (name)
            { 
                case "GetDateTimeWithLongDate": //当前日期，2011年4月3日
                    return DateTime.Now.ToLongDateString();
                case "GetDateTimeWithShortDate": //当前日期, 2011/4/3
                    return DateTime.Now.ToShortDateString();
                case "GetDateTimeWithLDateAndDayOfWeek": //当前日期+星期几，2011年4月3日 星期天
                    switch (DateTime.Now.DayOfWeek)
                    {
                        case DayOfWeek.Monday:
                            return DateTime.Now.ToLongDateString() + "　　星期一";
                        case DayOfWeek.Tuesday:
                            return DateTime.Now.ToLongDateString() + "　　星期二";
                        case DayOfWeek.Wednesday:
                            return DateTime.Now.ToLongDateString() + "　　星期三";
                        case DayOfWeek.Thursday:
                            return DateTime.Now.ToLongDateString() + "　　星期四";
                        case DayOfWeek.Friday:
                            return DateTime.Now.ToLongDateString() + "　　星期五";
                        case DayOfWeek.Saturday:
                            return DateTime.Now.ToLongDateString() + "　　星期六";
                        case DayOfWeek.Sunday:
                            return DateTime.Now.ToLongDateString() + "　　星期天";
                    }
                    return "";
                case "GetDateTimeWithSDateAndDayOfWeek": //当前日期+星期几，2011/4/3 星期天
                    switch (DateTime.Now.DayOfWeek)
                    {
                        case DayOfWeek.Monday:
                            return DateTime.Now.ToShortDateString() + "　　星期一";
                        case DayOfWeek.Tuesday:
                            return DateTime.Now.ToShortDateString() + "　　星期二";
                        case DayOfWeek.Wednesday:
                            return DateTime.Now.ToShortDateString() + "　　星期三";
                        case DayOfWeek.Thursday:
                            return DateTime.Now.ToShortDateString() + "　　星期四";
                        case DayOfWeek.Friday:
                            return DateTime.Now.ToShortDateString() + "　　星期五";
                        case DayOfWeek.Saturday:
                            return DateTime.Now.ToShortDateString() + "　　星期六";
                        case DayOfWeek.Sunday:
                            return DateTime.Now.ToShortDateString() + "　　星期天";
                    }
                    return "";
                case "GetTitleAndKeyWord": //获取标题和关键字
                    return SystemMethods.GetTitleAndKeyWord(copName);
                default:
                    return "";
            }
        }
        /// <summary>
        /// 反射程序集读取数据
        /// </summary>
        /// <param name="name"></param>
        /// <param name="copName"></param>
        /// <returns></returns>
        static List<DefaultDataPack> ReflectionMethod(string name, string copName)
        {
            XElement xe = XElement.Load(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/Config/reflection.config");
            XElement node = xe.Element(name.ToLower());
            XElement methodInfo = node.Element("methodInfo");
            //var module = serviceClient.GetModule(methodInfo.Element("assembly").Value);
            var module = serviceClient.GetType(methodInfo.Element("assembly").Value);
            var method = module.GetMethod(methodInfo.Element("method").Value);
            
            //var instance = serviceClient.CreateInstance(methodInfo.Element("assembly").Value);
            //var method = instance.GetType().GetMethod(methodInfo.Element("method").Value);
            var parmsele = node.Element("parameters").Elements("add").ToList();
            List<object> parms = new List<object>();
            for (int i = 0; i < parmsele.Count(); i++)
            {
                Type type = Type.GetType(parmsele[i].Attribute("type").Value);
                object result = GetParmsWithGetMode(parmsele[i].Attribute("getmode").Value,
                    parmsele[i].Attribute("pickkey").Value, copName, parmsele[i].Element("default").Value);
                result = result ?? 0; 
                parms.Add(CheckParamType(result, type));
            }
            return (List<DefaultDataPack>)method.Invoke(null, parms.Any() ? parms.ToArray() : null);
        }
        static object CheckParamType(object paramVal, Type type)
        {
            try
            {
                return Convert.ChangeType(paramVal, type);
            }
            catch
            {
                if (type == typeof(System.String))
                {
                    return String.Empty;
                }
                else if (type == typeof(System.Int32))
                {
                    return 0;
                }
                else
                {
                    return null;
                }
            }
        }
        /// <summary>
        /// 准备参数
        /// </summary>
        /// <param name="getmode"></param>
        /// <param name="getkey"></param>
        /// <param name="copName"></param>
        /// <param name="defaultval"></param>
        /// <returns></returns>
        static object GetParmsWithGetMode(string getmode, string getkey,string copName, string defaultval)
        {
            switch (getmode.ToLower())
            { 
                case "copname":
                    return copName;
                case "querystring":
                    string rawurl = HttpContext.Current.Request.RawUrl;
                    if (rawurl.IndexOf('?') > 0)
                    {
                        var qs = rawurl.Substring(rawurl.LastIndexOf('?') + 1)
                            .Split('&')
                            .Where(c =>
                                {
                                    if (String.IsNullOrEmpty(c))
                                    {
                                        return false;
                                    }
                                    if (c.ToLower().Contains(getkey.ToLower()))
                                    {
                                        return true;
                                    }
                                    return false;
                                });
                        if (qs.Any() && qs.First().Contains("="))
                        {
                            string pv = qs.First();
                            return pv.Substring(pv.IndexOf('=') + 1);
                        }
                    }
                    return defaultval;
                case "session":
                    if (HttpContext.Current.Session == null)
                    {
                        EmpiresLogger.ErrorLog("对反射程序准备参数时出错，getmode为session，但httpcontext中session为null", "Empires.PL.PageBuilder.BodyAnalyzer");    
                    }
                    if (HttpContext.Current.Session[getkey] == null)
                    {
                        EmpiresLogger.ErrorLog(String.Format("对反射程序准备参数时出错，请求session key为：{0}，Session[{0}]为null", getkey), "Empires.PL.PageBuilder.BodyAnalyzer");   
                    }
                    return HttpContext.Current.Session[getkey];
                case "application":
                    if (HttpContext.Current.Application[getkey] == null)
                    {
                        EmpiresLogger.ErrorLog(String.Format("对反射程序准备参数时出错，请求Application key为：{0}，Application[{0}]为null", getkey), "Empires.PL.PageBuilder.BodyAnalyzer");   
                    }
                    return HttpContext.Current.Application[getkey];
                default:
                    EmpiresLogger.ErrorLog(String.Format("反射程序准备参数时出错"), "Empires.PL.PageBuilder.BodyAnalyzer");
                    break;
            }
            return null;
        }
        static string FileHTML(string empelement, List<DefaultDataPack> data)
        {
            string modeType = string.Empty;
            var items = FilterSource(empelement).ToList();
            StringBuilder sb = new StringBuilder();
            foreach (var item in items)
            {
                switch (item.Label.labelName.ToLower())
                {
                    case "text":
                        sb.Append(item.Temp);
                        break;
                    case "fill":
                        switch (item.Label.Mode.ToLower())
                        {
                            case "text":
                                sb.Append(GetDataWithModePickerForTextMode(data, 0, item));
                                break;
                            case "repeat":
                                sb.Append(GetDataWithModePickerForRepeatMode(data, item));
                                break;
                            default:
                                return "";
                        }
                        break;
                }
            }
            return sb.ToString();
        }
        static IEnumerable<CatchMode> FilterSource(string empelement)
        {
            Regex reg = new Regex(PageBuilderRegexpLib.IgnoreLabel, RegexOptions.IgnoreCase);
            empelement = reg.Replace(empelement, "");//删除ignore节点下所有字符串

            reg = new Regex(PageBuilderRegexpLib.EmpiresInnerText, RegexOptions.IgnoreCase);
            empelement = reg.Match(empelement).Groups[0].ToString(); //剥离empires标签

            Queue<string> queue = new Queue<string>();
            reg = new Regex(PageBuilderRegexpLib.TextOrFillLabel, RegexOptions.IgnoreCase);
            var matchs = reg.Matches(empelement);
            string piece = string.Empty;
            foreach (var match in matchs)
            {
                piece = match.ToString();
                if (String.IsNullOrEmpty(piece))
                {
                    continue;
                }
                queue.Enqueue(piece);
            }
            int count = queue.Count;
            CatchMode mode = null;
            for (int i = 0; i < count; i++)
            {
                mode = new CatchMode();
                piece = queue.Dequeue();
                mode.Label = CatchLabel(piece);
                mode.Temp = CatchLabelInnerText(piece);
                if (mode.Label.labelName == "text")
                {
                    yield return mode;
                }
                else
                {
                    mode.Mode = GetCatchMode(piece);
                    yield return mode;
                }

            }
        }
        static LabelPack CatchLabel(string input)
        {
            Regex reg = new Regex(PageBuilderRegexpLib.LabelCatch, RegexOptions.IgnoreCase);
            var match = reg.Match(input);
            string item = match.Groups["item"].ToString();
            int time = 1;
            if (!String.IsNullOrEmpty(item))
            {
                if (!Int32.TryParse(item, out time))
                {
                    time = 1;
                }
            }
            return new LabelPack()
            {
                labelName = match.Groups["label"].ToString(),
                Mode = match.Groups["mode"].ToString(),
                Item = time
            };
        }
        static ModePack GetCatchMode(string input)
        {
            Regex reg = new Regex(PageBuilderRegexpLib.ModeCatch, RegexOptions.IgnoreCase);
            Match matchs = reg.Match(input);
            return new ModePack()
            {
                DefaultVal = matchs.Groups["def"].ToString(),
                Field = matchs.Groups["field"].ToString(),
                Index = matchs.Groups["idx"].ToString(),
                SubString = matchs.Groups["sub"].ToString()
            };
        }
        static string CatchLabelInnerText(string input)
        {
            Regex reg = new Regex(PageBuilderRegexpLib.LabelInner, RegexOptions.IgnoreCase);
            return reg.Match(input).Groups["text"].ToString();
        }

        static string GetDataWithModePickerForRepeatMode(List<DefaultDataPack> data, CatchMode pack)
        {
            StringBuilder sb = new StringBuilder();
            int repeatTime = Math.Min(data.Count, pack.Label.Item);
            CatchMode packTemp;
            for (int x = 0; x < repeatTime; x++)
            {
                packTemp = CloneCatchMode(pack);
                sb.Append(GetDataWithModePickerForTextMode(data, x, packTemp));
            }
            return sb.ToString();
        }
        static CatchMode CloneCatchMode(CatchMode target)
        {
            CatchMode newOne = new CatchMode();
            newOne.Label = new LabelPack();
            newOne.Mode = new ModePack();

            newOne.Label.Item = target.Label.Item;
            newOne.Label.labelName = target.Label.labelName;
            newOne.Label.Mode = target.Label.Mode;
            newOne.Mode.DefaultVal = target.Mode.DefaultVal;
            newOne.Mode.Field = target.Mode.Field;
            newOne.Mode.Index = target.Mode.Index;
            newOne.Mode.SubString = target.Mode.SubString;
            newOne.Temp = target.Temp;
            return newOne;
        }
        static string GetDataWithModePickerForTextMode(List<DefaultDataPack> data, int defrow, CatchMode pack)
        {
            
            Regex reg = new Regex(PageBuilderRegexpLib.FiledPick, RegexOptions.IgnoreCase);
            var match = reg.Matches(pack.Temp);
            for (int i = 0; i < match.Count; i++)
            {
                var mode = GetCatchMode(match[i].Value);
                int idx = defrow;
                if (Int32.TryParse(mode.Index, out idx))
                {
                    idx = idx < data.Count - 1 ? idx : defrow;
                }
                else
                {
                    idx = defrow;
                }
                DefaultDataPack datarow = null;
                if (data.Count == 0)
                {
                    datarow = new DefaultDataPack();
                }
                else
                {
                    datarow = data[idx];
                }
                var col = datarow.GetType().GetProperty(mode.Field);
                object o_colval = col == null ? null : col.GetValue(datarow, null);
                string colval = o_colval != null ? o_colval.ToString() : String.Empty;
                if (String.IsNullOrEmpty(colval))
                {
                    colval = mode.DefaultVal;
                }
                if (!String.IsNullOrEmpty(mode.SubString))
                {
                    string startStr = mode.SubString.Remove(mode.SubString.IndexOf(','));
                    string endStr = mode.SubString.Substring(mode.SubString.IndexOf(',') + 1);
                    int start = 0;
                    int end = 0;
                    Int32.TryParse(startStr, out start);
                    Int32.TryParse(endStr, out end);
                    int length = colval.Length;
                    start = (start >= 0 && start < length - 1) ? start : 0;
                    end = (end > start && end < length - 1) ? end : length - 1;
                    colval = colval.Substring(start, end - start + 1);
                }
                pack.Temp = pack.Temp.Replace(match[i].Value, colval);
            }
            //处理条件判断where标签
            reg = new Regex(PageBuilderRegexpLib.WhereLabel, RegexOptions.IgnoreCase);
            var expmatch = reg.Matches(pack.Temp);
            if (expmatch.Count>0) //如果匹配成功
            {
                for (int i = 0; i < expmatch.Count; i++)
                {
                    var x = expmatch[i].Value;
                    string left = expmatch[i].Groups["left"].Value; //获得左表达式
                    string sign = expmatch[i].Groups["sign"].Value; //获得符号
                    string right = expmatch[i].Groups["right"].Value; //获得右表达式
                    int processresult = 1; //1:包含, 0:忽略 默认包含
                    #region 条件判断
                    if (!String.IsNullOrEmpty(left) && !String.IsNullOrEmpty(sign) && !String.IsNullOrEmpty(right))
                    {
                        int rightvalue = 0;
                        int leftvalue = 0;
                        switch (sign)
                        { 
                            case ">=":
                                if (Int32.TryParse(right, out rightvalue) && Int32.TryParse(left, out leftvalue))
                                {
                                    if (leftvalue >= rightvalue)
                                    {
                                        processresult = 1;
                                    }
                                    else
                                    {
                                        processresult = 0;
                                    }
                                }
                                break;
                            case "<=":
                                if (Int32.TryParse(right, out rightvalue) && Int32.TryParse(left, out leftvalue))
                                {
                                    if (leftvalue <= rightvalue)
                                    {
                                        processresult = 1;
                                    }
                                    else
                                    {
                                        processresult = 0;
                                    }
                                }
                                break;
                            case ">":
                                if (Int32.TryParse(right, out rightvalue) && Int32.TryParse(left, out leftvalue))
                                {
                                    if (leftvalue > rightvalue)
                                    {
                                        processresult = 1;
                                    }
                                    else
                                    {
                                        processresult = 0;
                                    }
                                }
                                break;
                            case "<":
                                if (Int32.TryParse(right, out rightvalue) && Int32.TryParse(left, out leftvalue))
                                {
                                    if (leftvalue < rightvalue)
                                    {
                                        processresult = 1;
                                    }
                                    else
                                    {
                                        processresult = 0;
                                    }
                                }
                                break;
                            case "==":
                                if (Int32.TryParse(right, out rightvalue) && Int32.TryParse(left, out leftvalue))
                                {
                                    if (leftvalue == rightvalue)
                                    {
                                        processresult = 1;
                                    }
                                    else
                                    {
                                        processresult = 0;
                                    }
                                }
                                else
                                {
                                    if (left.ToLower() == right.ToLower())
                                    {
                                        processresult = 1;
                                    }
                                    else
                                    {
                                        processresult = 0;
                                    }
                                }
                                break;
                            case "!=":
                                if (Int32.TryParse(right, out rightvalue) && Int32.TryParse(left, out leftvalue))
                                {
                                    if (leftvalue != rightvalue)
                                    {
                                        processresult = 1;
                                    }
                                    else
                                    {
                                        processresult = 0;
                                    }
                                }
                                else
                                {
                                    if (left.ToLower() != right.ToLower())
                                    {
                                        processresult = 1;
                                    }
                                    else
                                    {
                                        processresult = 0;
                                    }
                                }
                                break;
                        }
                    }
                    #endregion
                    if (processresult == 0)
                    {
                        pack.Temp = pack.Temp.Replace(expmatch[i].Value, "");
                    }
                    else
                    {
                        pack.Temp = pack.Temp.Replace(expmatch[i].Value, expmatch[i].Groups["content"].Value);
                    }
                }
            }
            return pack.Temp;
        }

        class CatchMode
        {
            public LabelPack Label { get; set; }
            public string Temp { get; set; }
            public ModePack Mode { get; set; }
        }
        class LabelPack
        {
            public string labelName { get; set; }
            public string Mode { get; set; }
            public int Item { get; set; }
        }
        class ModePack
        {
            public string Field { get; set; }
            public string Index { get; set; }
            public string SubString { get; set; }
            public string DefaultVal { get; set; }
        }
    }
}
